<?php
/**
 * 微信粉丝扩展.
 * User: Administrator
 * Date: 2019/12/9 0009
 * Time: 10:37
 */

namespace app\admin\traits\controller;


use service\DataService;
use service\LogService;
use service\WechatService;
use think\Db;

Trait WxFans{

    /**
     * 列表后置方法
     */
    protected function _data_filter(&$data){
        $tag_list = Db::name('wechat_fans_tags')->column('name', 'id');
        foreach ($data as &$vo) {
            $tmp_tag = [];
            if(!empty($vo['tagid_list'])){
                foreach (explode(',',$vo['tagid_list']) as $tagid) {
                    $tmp_tag[] = $tag_list[$tagid];
                }
            }
            $vo['tag_list'] = implode(',',$tmp_tag);
        }
    }

    /**
     * 粉丝标签选择表单后置方法(提交是前置方法)
     */
    protected function _tagset_form_filter(&$data){
        if($this->request->isPost()){
            $fans = Db::name($this->table)->where('id', $data['id'])->find();
            empty($fans) && $this->error('需要操作的数据不存在!');
            $choose_tagids = explode(',',$fans['tagid_list']);
            $equal_tagids = [];
            if(isset($data['tag_ids'])){
                $equal_tagids = array_intersect($data['tag_ids'],$choose_tagids);
            }
            $wechat = load_wechat('User');
            //需要删除的标签
            if($delete_tagids = array_diff($choose_tagids,$equal_tagids)){
                foreach($delete_tagids as $tagid){
                    is_numeric($tagid) && $wechat->batchDeleteUserTag($tagid, [$fans['openid']]);
                }
            }
            //需要新增的标签
            if(isset($data['tag_ids']) && $set_tagids = array_diff($data['tag_ids'],$equal_tagids)){
                foreach($set_tagids as $tagid){
                    is_numeric($tagid) && $wechat->batchAddUserTag($tagid, [$fans['openid']]);
                }
            }
            $data['tagid_list'] = isset($data['tag_ids']) ? implode(',',$data['tag_ids']) : '';
            unset($data['tag_ids']);
        }
        if($this->request->isGet()) {
            $tag_list = Db::name('wechat_fans_tags')->column('name', 'id');
            $data['tag_list'] = $tag_list;
            is_string($data['tagid_list']) && $data['tagid_list'] = explode(',', $data['tagid_list']);
        }
    }

    /**
     * 删除粉丝标签
     */
    protected function _delete(&$data){
        $wechat = load_wechat('User');
        $status = DataService::update($this->table);
        if(false !== $status && false !== $wechat->delTag($data['id'])){
            return true;
        }
        return false;
    }

    /**
     * 同步粉丝标签
     */
    protected function _sync(){
        $table_name = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $this->table));
        Db::query("truncate table {$table_name}");
        //进行同步
        if(WechatService::syncAllFans('')){
            WechatService::syncBlackFans('');
            LogService::write('微信管理','同步全部微信粉丝标签成功');
            return true;
        }
        return false;
    }

    /**
     * 拉入黑名单
     */
    protected function _addBack($param){
        $wechat = load_wechat('User');
        $status = false;
        $msg = "设备黑名单失败，请稍候再试！{$wechat->errMsg}[{$wechat->errCode}]";
        $openids = $this->_getActionOpenids($param['id']);
        if (false !== $wechat->addBacklist($openids)) {
            Db::name($this->table)->where('openid', 'in', $openids)->setField('is_back', '1');
            $status = true;
            $msg = "已成功将 " . count($openids) . " 名粉丝移到黑名单!";
        }
        return rstReturn($status,$msg);
    }

    /**
     * 移除黑名单
     */
    protected function _delBack($param){
        $wechat = load_wechat('User');
        $status = false;
        $msg = "设备黑名单失败，请稍候再试！{$wechat->errMsg}[{$wechat->errCode}]";
        $openids = $this->_getActionOpenids($param['id']);
        if (false !== $wechat->delBacklist($openids)){
            Db::name($this->table)->where('openid', 'in', $openids)->setField('is_back', '0');
            $status = true;
            $msg = "已成功将 " . count($openids) . " 名粉丝从黑名单中移除!";
        }
        return rstReturn($status,$msg);
    }

    /**
     * 获取当前操作用户openid数组
     * @return array
     */
    private function _getActionOpenids($ids)
    {
        empty($ids) && $this->error('没有需要操作的数据!');
        $openids = Db::name($this->table)->where('id', 'in', explode(',', $ids))->column('openid');
        empty($openids) && $this->error('没有需要操作的数据!');
        return $openids;
    }

}